package com.qianchang.microfinance.view.yfbpay;

import android.annotation.SuppressLint;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;

import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.FormatUtil;
import com.dm.library.utils.StringUtils;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.ClearEditText;
import com.dm.library.widgets.element.DTextView;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.QueryBankCardBean;
import com.qianchang.microfinance.bean.SigApyConfBean;
import com.qianchang.microfinance.bean.ThpinfoBean;
import com.qianchang.microfinance.bean.YBApplyinfoBean;
import com.qianchang.microfinance.global.DMApplication;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.BaseActivity;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

import static com.qianchang.microfinance.global.ConstantAppInfo.DEFAULT_TIME;


/***
 * 易宝支付录入 界面    2018.8.21
 */

public class YBPayInputActivity extends BaseActivity{


//    CheckBox cbDebitCard;
//    CheckBox cbCreditCard;
    @BindView(R.id.ce_name_id)
    ClearEditText ceUserName;
    @BindView(R.id.ce_phone_id)
    ClearEditText phoneNub;
    @BindView(R.id.tv_get_phone_code)
    DTextView tvGetPhoneCode;
    @BindView(R.id.ll_cvv2_id)
    LinearLayout llCvv2Layout;
    @BindView(R.id.ll_validper_id)
    LinearLayout llValidper;
    @BindView(R.id.bank_card_no_tv)
    ClearEditText EdBankNub;
    @BindView(R.id.ce_idnub_id)
    ClearEditText edIdNub;
    @BindView(R.id.ce_validper_id)
    ClearEditText ceValidper;
    @BindView(R.id.ce_cvv2_id)
    ClearEditText ceCVV2;
    @BindView(R.id.et_phone_indentify_code)
    ClearEditText ceIndentify;


    private CountDownTimer phoneDownTimer;
    private static int ADDCARD_RESCODE = 6;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yfbpayinput_layout);
        ButterKnife.bind(this);
        initView();

    }


    @Override
    protected void initView() {
        super.initView();
        setTitle("绑定银行卡");

        EdBankNub.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View view, boolean b) {
                if(!b){
                    queryBankCard();                //查询卡是否有效
                }
            }
        });
    }



    @OnCheckedChanged({R.id.cb_debit_card_id,R.id.cb_credit_card_id})
    public void OnCheckedChangeListener(CompoundButton view, boolean ischanged){
        switch (view.getId()){
            case R.id.cb_debit_card_id:         //借记卡选择
                if (ischanged){
                    setCreditCardViewIsShow(R.id.cb_debit_card_id);
                }
                break;
            case R.id.cb_credit_card_id:            //信用卡选择
                if (ischanged){
                    setCreditCardViewIsShow(R.id.cb_credit_card_id);
                }
                break;
            default:
                break;
        }
    }

    //选中不同类型卡，显示或者隐藏不同输入选项
    private void setCreditCardViewIsShow(int id){
        if(id == R.id.cb_debit_card_id){        //借记卡
//            cbCreditCard.setChecked(false);
            llCvv2Layout.setVisibility(View.GONE);      //当选择借卡的时候有效期和CVV2 隐藏视图
            llValidper.setVisibility(View.GONE);
        }else if(id == R.id.cb_credit_card_id){         //信用卡
            llCvv2Layout.setVisibility(View.VISIBLE);       //当选择借卡的时候有效期和CVV2 显示视图
            llValidper.setVisibility(View.VISIBLE);
//            cbDebitCard.setChecked(false);
        }
    }




    @OnClick({R.id.bt_payapply_id,R.id.tv_get_phone_code})
    public void onViewClicked(View view) {
        int vid = view.getId();
        switch (vid){
            case R.id.bt_payapply_id:           //提交申请按钮

                verificationPayapply();

                break;
            case R.id.tv_get_phone_code:        //获取短信验证码

                verification();

                break;
            default:
                break;
        }
    }



    /**
     * 向 获取手机验证码
     */
    private void getPhoneCode() {
        String s_phone = phoneNub.getText().toString().trim();
        if (!FormatUtil.isValidPhone(s_phone, null)) {
            ToastUtil.getInstant().show(this, getString(R.string.msg_input_correct_account));
            return;
        }

        if (s_phone.length() >= 3) {
            String subStr = s_phone.substring(0, 3);
            if (subStr.equals("170") || subStr.equals("171") || subStr.equals("145") || subStr.equals("147")) {
                ToastUtil.getInstant().show(this, "该手机号无效");
                return;
            }
        }
    }

//    private static final int DEFAULT_TIME = 10 * 1000;//获取验证码的时间周期      测试使用，不用时候直接删掉
    //显示获取手机验证码倒计时
    private void showRemainTime() {
        tvGetPhoneCode.setEnabled(false);
        phoneDownTimer = new CountDownTimer(DEFAULT_TIME, 1000) {
            @SuppressLint("NewApi")
            @Override
            public void onTick(long millisUntilFinished) {
                int temp = (int) (millisUntilFinished / 1000);
                tvGetPhoneCode.setText("重新获取 " + temp + "S");//getString(R.string.remain_time) +
                tvGetPhoneCode.setEnabled(false);
                Resources res = getResources();
                tvGetPhoneCode.setTextColor(ContextCompat.getColor(getApplicationContext(),R.color.common_text_hint_color));
            }

            @SuppressLint("NewApi")
            @Override
            public void onFinish() {
                tvGetPhoneCode.setText(getString(R.string.btn_reacquire_code));
                tvGetPhoneCode.setEnabled(true);
                tvGetPhoneCode.setTextColor(ContextCompat.getColor(getApplicationContext(),R.color.getCodeTextColor_blue));
            }
        }.start();

    }


    private void verificationPayapply(){

        String cardNub = EdBankNub.getText().toString();
        String idNub = edIdNub.getText().toString();
        String userName = ceUserName.getText().toString();
        String s_phone = phoneNub.getText().toString().trim();
        String ceVali = ceValidper.getText().toString();
        String ceCV = ceCVV2.getText().toString();
        String ceInden  = ceIndentify.getText().toString();

        if(StringUtils.isEmptyOrNull(cardNub)){
            ToastUtil.getInstant().show(YBPayInputActivity.this, getString(R.string.input_carnub));
            return;
        }

        if(StringUtils.isEmptyOrNull(idNub)){
            ToastUtil.getInstant().show(YBPayInputActivity.this, getString(R.string.input_idnub));
            return;
        }

        if (!FormatUtil.isValidIdCard(idNub.trim())) {
            ToastUtil.getInstant().show(YBPayInputActivity.this, getString(R.string.msg_idCard_not_ok));
            return;
        }


        if(StringUtils.isEmptyOrNull(userName)){
            ToastUtil.getInstant().show(YBPayInputActivity.this, getString(R.string.input_name));
            return;
        }

        if (StringUtils.isEmptyOrNull(s_phone)) {
            ToastUtil.getInstant().show(YBPayInputActivity.this, getString(R.string.msg_please_input_phone_number));
            return;
        }

        if (!FormatUtil.isValidPhone(s_phone, null)) {
            ToastUtil.getInstant().show(this, getString(R.string.msg_input_correct_account));
            return;
        }

        if (StringUtils.isEmptyOrNull(ceInden)) {
            ToastUtil.getInstant().show(this, getString(R.string.input_indentity));
            return;
        }

        signedApplyConfirm();   //确认申请绑定

    }


    private void verification(){

        String cardNub = EdBankNub.getText().toString();
        String idNub = edIdNub.getText().toString();
        String userName = ceUserName.getText().toString();
        String s_phone = phoneNub.getText().toString().trim();
        String ceVali = ceValidper.getText().toString();
        String ceCV = ceCVV2.getText().toString();
        String ceInden  = ceIndentify.getText().toString();


        if(StringUtils.isEmptyOrNull(cardNub)){
            ToastUtil.getInstant().show(YBPayInputActivity.this, getString(R.string.input_carnub));
            return;
        }


        if(StringUtils.isEmptyOrNull(idNub)){
            ToastUtil.getInstant().show(YBPayInputActivity.this, getString(R.string.input_idnub));
            return;
        }

        if (!FormatUtil.isValidIdCard(idNub.trim())) {
            ToastUtil.getInstant().show(YBPayInputActivity.this, getString(R.string.msg_idCard_not_ok));
            return;
        }


        if(StringUtils.isEmptyOrNull(userName)){
            ToastUtil.getInstant().show(YBPayInputActivity.this, getString(R.string.input_name));
            return;
        }

        if (StringUtils.isEmptyOrNull(s_phone)) {
            ToastUtil.getInstant().show(YBPayInputActivity.this, getString(R.string.msg_please_input_phone_number));
            return;
        }

        if (!FormatUtil.isValidPhone(s_phone, null)) {
            ToastUtil.getInstant().show(this, getString(R.string.msg_input_correct_account));
            return;
        }


        showRemainTime();               //倒计时
        if(getIsApplySus()){            //第二步，如果签约申请成功，重发签约短信验证码
            resendSigning();
        }else {
            ybPayApply();           //第一步,先签约申请
        }

    }

    //交易透传信息 签约申请时返回,如果不为空,则原样带上
    private YBApplyinfoBean thpinfoBean = null;
    public YBApplyinfoBean getThpinfoBean() {
        return thpinfoBean;
    }

    public void setThpinfoBean(YBApplyinfoBean thpinfoBean) {
        this.thpinfoBean = thpinfoBean;
    }

    //设置签约申请成功标识
    private boolean isApplySus = false;
    private void setIsApplySus(boolean flag){
        this.isApplySus = flag;
    }

    private boolean getIsApplySus(){
        return isApplySus;
    }


    //输入卡号检测是否有效
    private boolean isValid = false;

    public boolean getIsValid() {
        return isValid;
    }
    public void setValid(boolean valid) {
        isValid = valid;
    }


    /****
     *      查询银行卡信用卡是否可用
     */

    private void queryBankCard(){

        String acctno = EdBankNub.getText().toString();
        if(acctno == null || acctno.equals("")){
            return;
        }

        HttpParams params = new HttpParams();
        params.put("cardno",acctno);

        show();
        DMOKHttpUtils.getInstance().post(YBPayInputActivity.this, DMConstant.ApiURL.YEPAY_QUERYBANKCARD, params, new RequestCallBack<QueryBankCardBean>() {

            @Override
            public void onSuccess(JsonResult<QueryBankCardBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    QueryBankCardBean queryBankCardBean = response.getObject();
                    String valid = queryBankCardBean.getIsvalid();                  // VALID 有效，INVALID无效
                    if(valid.equals("VALID")){
                        setValid(true);
                    }else {
                        setValid(false);
                        ToastUtil.getInstant().show(YBPayInputActivity.this,"卡无效!");
                    }
                }else {
                    setValid(false);
                    ToastUtil.getInstant().show(YBPayInputActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                setValid(false);
                ToastUtil.getInstant().show(YBPayInputActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });

    }




    /***
     * 易宝支付申请
     */
    private void ybPayApply(){


//        String acctno = "5218990771581880";       //信用卡   测试使用
//        String idno = "452601198311150323";
//        String acctname = "黄小川";
//        String mobile = "13707818378";

        String acctno = EdBankNub.getText().toString();
        String idno = edIdNub.getText().toString();
        String acctname = ceUserName.getText().toString();
        String mobile = phoneNub.getText().toString();
        String userId = DMApplication.getInstance().getmUserLoginInfo().getUserId();


        HttpParams params = new HttpParams();
        params.put("userId",userId);
        params.put("cardno",acctno);                //银行卡号
        params.put("idcardno",idno);                    //证件号
        params.put("username",acctname);            //户名
        params.put("phone",mobile);                //手机号码


        DMOKHttpUtils.getInstance().post(YBPayInputActivity.this, DMConstant.ApiURL.YEPAY_SIGNEDAPPLY, params, new RequestCallBack<YBApplyinfoBean>() {

            @Override
            public void onSuccess(JsonResult<YBApplyinfoBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    setIsApplySus(true);    //设置签约申请是否请求成功
                    setThpinfoBean(response.getObject());
                }
                else {
                    setIsApplySus(false);
                    setThpinfoBean(null);
                    ToastUtil.getInstant().show(YBPayInputActivity.this, response.getObject().toString());
                    ToastUtil.getInstant().show(YBPayInputActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                setIsApplySus(false);
                setThpinfoBean(null);
                ToastUtil.getInstant().show(YBPayInputActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
                setIsApplySus(false);
                setThpinfoBean(null);
            }
        });
    }

    private String spitValitStr(String str){
        boolean isCont = str.contains("/");
        String instr = "";
        if(isCont){
            String[] names = str.split("/");
            for(int i = 0; i < names.length; i++){
                instr = instr + names[i];
            }
        }else {
            instr = str;
        }
        return instr;
    }



    //重发签约短信验证码
    private void resendSigning(){

//        String acctno = "6217003370019590";
//        String idno = "4509231985101335";
//        String acctname = "陈广林";
//        String mobile = "187769000";


//        String acctno = "5218990771581880";       //信用卡   测试使用
//        String idno = "452601198311150323";
//        String acctname = "黄小川";
//        String mobile = "13707818378";


        YBApplyinfoBean ybApplyinfoBean = getThpinfoBean();
        String reqNo = "";
        if(ybApplyinfoBean != null){
            reqNo = ybApplyinfoBean.getRequestno();
        }
        HttpParams params = new HttpParams();
        params.put("requestno",reqNo);


        DMOKHttpUtils.getInstance().post(YBPayInputActivity.this, DMConstant.ApiURL.YEPAY_RESENDSIGNEDCAPTCHA, params, new RequestCallBack<ThpinfoBean>() {

            @Override
            public void onSuccess(JsonResult<ThpinfoBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {

                }else {
                    ToastUtil.getInstant().show(YBPayInputActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(YBPayInputActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }



    //签约申请确认
    private void signedApplyConfirm(){


//        String acctno = "5218990771581880";       //信用卡   测试使用
//        String idno = "452601198311150323";
//        String acctname = "黄小川";
//        String mobile = "13707818378";


        String smscode = ceIndentify.getText().toString();
        String meruserid = DMApplication.getInstance().getmUserLoginInfo().getUserId();

        YBApplyinfoBean ybApplyinfoBean = getThpinfoBean();
        String reqNo = "";
        if(ybApplyinfoBean != null){
            reqNo = ybApplyinfoBean.getRequestno();
        }

        HttpParams params = new HttpParams();
        params.put("userId",meruserid);
        params.put("validatecode",smscode);
        params.put("requestno",reqNo);

        DMOKHttpUtils.getInstance().post(YBPayInputActivity.this, DMConstant.ApiURL.YEPAY_SIGNEDAPPLYCONFIRM, params, new RequestCallBack<SigApyConfBean>() {

            @Override
            public void onSuccess(JsonResult<SigApyConfBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
//                    ToastUtil.getInstant().show(TlPayInputActivity.this,"绑定卡成功!");
                    toReSult();
                    setResult(ADDCARD_RESCODE);
                    YBPayInputActivity.this.finish();
                }else {
                    ToastUtil.getInstant().show(YBPayInputActivity.this,response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(YBPayInputActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    private void toReSult(){
        Bundle bundle = new Bundle();
        bundle.putInt("typeInt",1);
        startActivity(YBSusOrFailActivity.class,bundle);
    }

}
